import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    // 后续可能要改成username
    username: '',
    imagePath: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.username = name
  },
  SET_AVATAR: (state, avatar) => {
    state.imagePath = avatar
  }
}

const actions = {
  // 处理请求
  async  login({ commit }, userInfo) {
    // 解构出用户名和密码
    const { account, password ,role } = userInfo;
    // 进行登录请求
    let result  = await login({account : account.trim() , password : password ,role:role});
    // 成功设置Token,mock中模拟的成功code为20000
    if(result.code == 200){
      commit('SET_TOKEN',result.data.token);
      setToken(result.data.token);
      return 'OK';
    }else{
      return Promise.reject(new Error('账号或者用户名错误'))
    }
  },

  // 得到用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response
        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { username, imagePath } = data

        commit('SET_NAME', username)
        commit('SET_AVATAR', imagePath)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 退出
  async logout({ commit, state }) {
    let res = await logout(state.token);
    if(res.code == 200){
      removeToken(); // 移除token
      resetRouter(); // 重置路由
      commit('RESET_STATE');
    }else{
      return Promise.reject(new Error('Network Error'));
    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  setAvatar(miniStore,val){
    miniStore.commit('SET_AVATAR',val);
}
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

